﻿using Common;
using NB.MGJ.Common;
using NB.MGJ.Common.Helper;
using NB.MGJ.Common.MVC;
using NB.MGJ.Model;
using NB.MGJ.Service;
using NB.MGJ.Service.AntiFake;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace NB.MGJ.Web.Controllers
{
    public partial class MarketController : BaseController 
    {
        private MarketService _market = new MarketService();

        //  
        // GET: /Market/
        #region 移动端红包
        public ActionResult RedPack1()
        {
            return View("/Views/Mobile/RedPack1.cshtml");
        }
        public ActionResult RedPack2()
        {
            return View("/Views/Mobile/RedPack2.cshtml");
        }

        public ActionResult RedPack3()
        {
            return View("/Views/Mobile/RedPack3.cshtml");
        }


        #endregion

        #region 创建活动
        public ActionResult ErWeiMa()
        {
            return View();
        }
        public ActionResult CreateActivities()
        {
            return View();
        }
        /// <summary>
        /// 绑定产品批次下拉框
        /// </summary>
        /// <returns></returns>
        public JsonResult GetBatchList(string batchID="0" )
        {

            List<CodeManage_GenCodeBatch> result = LogOnUser.HeadId == 1
                ? _market.GetGenCodeListBox(LogOnUser.EnterpriseId, batchID)
                : _market.GetGenCodeListBox2(LogOnUser.EnterpriseId, batchID);
            return Json(result);
        }

        #region   抢红包
        /// <summary>
        /// 抢红包
        /// </summary>
        /// <param name="oper"></param>
        /// <param name="Aid"></param>
        /// <param name="ActivityType"></param>
        /// <returns></returns>
        public ActionResult RPActivity(string oper,int Aid=0,int ActivityType=2)
        {
           // ViewBag.Name = LogOnUser.EnterpriseName;
            ViewBag.Aid = Aid;
            ViewBag.Oper = oper;
            ViewBag.ActivityType = ActivityType;
            ViewBag.Ename = LogOnUser.EnterpriseName;
           //  var awardsList=new List<Marketing_Awards>();
            Marketing_All market=new Marketing_All();
            if (Aid != 0)    //编辑
            {
                market.activity = _market.GetActivityModel(Aid);//活动信息
                market.delivery = _market.GetDeliveryById(market.activity.DeliveryId.Value);
                market.webInfo = _market.GetActivityInfo(market.activity.ActivityInfoID ?? 0);
                market.awardsList = _market.GetAwards_Aid(Aid);
                
                //awardsList=_mserice.GetAwards_Aid(Aid);
            }
            else     //添加
            {
                                          
                market.activity = new Marketing_Activity();
                market.activity.StartDate = DateTime.Now;
                market.activity.EndDate = DateTime.Now.AddDays(7);
                market.activity.Title = "幸运抢红包";
                market.activity.RuleExplain = @"1.红包/验证码/预约券仅限购买meilele.com官网商品使用，不能兑换成现金。2、每个订单只能使用1个红包/验证码/预约券。3、在有效使用时间内使用，过期未使用自动作废。";
                market.activity.ParticipationNum = 100;
                market.delivery = new Marketing_Delivery();
                market.delivery.EachGetSumNum = "10";
                market.delivery.EachGetPrizeNum = "10";
                market.delivery.DayGetPrizeNum = "3";
                market.webInfo = new Marketing_ActivityInfo();
                market.webInfo.IsShowLogo = 0; //默认隐藏
                market.webInfo.ShareContont = "0";
                market.webInfo.Sponsor = LogOnUser.EnterpriseName;
                market.awardsList = new List<Marketing_Awards>();
                market.activity.ActivityType = ActivityType;
                market.activity.IsParticipationLimit = 1;
                market.webInfo.WXCodeImgUrl = "/Content/webImgs/upLogo/cp_img_tj.png";
                market.webInfo.ActivityCodeImg = "/Content/webImgs/upLogo/cp_img_tj.png";
                market.webInfo.ShareImgUrl = "/Content/webImgs/upLogo/cp_img_tj.png";
                market.webInfo.PagelaodImgUrl = "/Content/webImgs/upLogo/cp_img_tj.png";
                market.webInfo.LogoImgUrl = "/Content/webImgs/upLogo/cp_img_tj.png";
                market.webInfo.WxShareImg = "/Content/webImgs/upLogo/cp_img_tj.png";
                market.webInfo.BtnCodeImgUrl = "/Content/webImgs/upLogo/cp_img_tj.png";
                market.webInfo.BtnName = "自定义按钮";
                market.webInfo.IsShare = 1;
            }
           
            return View(market);
        }
        #endregion

        #region    九宫格
        /// <summary>
        /// 九宫格
        /// </summary>
        /// <param name="oper"></param>
        /// <param name="Aid"></param>
        /// <param name="ActivityType"></param>
        /// <returns></returns>
        public ActionResult TurntableActivity(string oper, int Aid = 0, int ActivityType = 1)
        {
            // ViewBag.Name = LogOnUser.EnterpriseName;
            ViewBag.Aid = Aid;
            ViewBag.Oper = oper;
            ViewBag.ActivityType = ActivityType;
            ViewBag.Ename = LogOnUser.EnterpriseName;
           //  var awardsList=new List<Marketing_Awards>();
            Marketing_All market=new Marketing_All();
            if (Aid != 0)    //编辑
            {
                market.activity = _market.GetActivityModel(Aid);//活动信息
                market.delivery = _market.GetDeliveryById(market.activity.DeliveryId.Value);
                market.webInfo = _market.GetActivityInfo(market.activity.ActivityInfoID ?? 0);
                market.awardsList = _market.GetAwards_Aid(Aid);
                
                //awardsList=_mserice.GetAwards_Aid(Aid);
            }
            else     //添加
            {


                market.activity = new Marketing_Activity();
                market.activity.IsParticipationLimit = 1;
                market.activity.StartDate = DateTime.Now;
                market.activity.EndDate = DateTime.Now.AddDays(7);
                market.activity.Title = "幸运九宫格";
                market.activity.RuleExplain = @"1.红包/验证码/预约券仅限购买meilele.com官网商品使用，不能兑换成现金。2、每个订单只能使用1个红包/验证码/预约券。3、在有效使用时间内使用，过期未使用自动作废。";
                market.activity.ParticipationNum = 100;
                market.delivery = new Marketing_Delivery();
                market.delivery.EachGetSumNum = "10";
                market.delivery.EachGetPrizeNum = "10";
                market.delivery.DayGetPrizeNum = "3";
                market.webInfo = new Marketing_ActivityInfo();
                market.webInfo.IsShowLogo = 0; //默认隐藏
                market.webInfo.ShareContont = "0";
                market.webInfo.Sponsor = LogOnUser.EnterpriseName;
                market.awardsList = new List<Marketing_Awards>();
                market.activity.ActivityType = ActivityType;
                market.webInfo.WXCodeImgUrl = "/Content/webImgs/upLogo/cp_img_tj.png";
                market.webInfo.ActivityCodeImg = "/Content/webImgs/upLogo/cp_img_tj.png";
                market.webInfo.ShareImgUrl = "/Content/webImgs/upLogo/cp_img_tj.png";
                market.webInfo.PagelaodImgUrl = "/Content/webImgs/upLogo/cp_img_tj.png";
                market.webInfo.LogoImgUrl = "/Content/webImgs/upLogo/cp_img_tj.png";
                market.webInfo.WxShareImg = "/Content/webImgs/upLogo/cp_img_tj.png";
                market.webInfo.BtnCodeImgUrl = "/Content/webImgs/upLogo/cp_img_tj.png";
                market.webInfo.BtnName = "自定义按钮";
                market.webInfo.IsShare = 1;

            }

            return View(market);
        }
        #endregion

        #region  砸金蛋
        /// <summary>
        /// 砸金蛋 
        /// </summary>
        /// <returns></returns>
        public ActionResult GoldEggsActivity(string oper, int Aid = 0, int ActivityType = 3)
        {
            // ViewBag.Name = LogOnUser.EnterpriseName;
            ViewBag.Aid = Aid;
            ViewBag.Oper = oper;
            ViewBag.ActivityType = ActivityType;
            ViewBag.Ename = LogOnUser.EnterpriseName;
            //  var awardsList=new List<Marketing_Awards>();
            Marketing_All market = new Marketing_All();
            if (Aid != 0)    //编辑
            {
                market.activity = _market.GetActivityModel(Aid);//活动信息
                market.delivery = _market.GetDeliveryById(market.activity.DeliveryId.Value);
                market.webInfo = _market.GetActivityInfo(market.activity.ActivityInfoID ?? 0);
                market.awardsList = _market.GetAwards_Aid(Aid);

                //awardsList=_mserice.GetAwards_Aid(Aid);
            }
            else     //添加
            {

                market.activity = new Marketing_Activity();
                market.activity.IsParticipationLimit = 1;
                market.activity.StartDate = DateTime.Now;
                market.activity.EndDate = DateTime.Now.AddDays(7);
                market.activity.Title = "砸蛋赢大奖";
                market.activity.RuleExplain = @"1.红包/验证码/预约券仅限购买meilele.com官网商品使用，不能兑换成现金。2、每个订单只能使用1个红包/验证码/预约券。3、在有效使用时间内使用，过期未使用自动作废。";
                market.activity.ParticipationNum = 100;
                market.delivery = new Marketing_Delivery();
                market.delivery.EachGetSumNum = "10";
                market.delivery.EachGetPrizeNum = "10";
                market.delivery.DayGetPrizeNum = "3";
                market.webInfo = new Marketing_ActivityInfo();
                market.webInfo.IsShowLogo = 0; //默认隐藏
                market.webInfo.ShareContont = "0";
                market.webInfo.Sponsor = LogOnUser.EnterpriseName;
                market.awardsList = new List<Marketing_Awards>();
                market.activity.ActivityType = ActivityType;
                market.webInfo.WXCodeImgUrl = "/Content/webImgs/upLogo/cp_img_tj.png";
                market.webInfo.ActivityCodeImg = "/Content/webImgs/upLogo/cp_img_tj.png";
                market.webInfo.ShareImgUrl = "/Content/webImgs/upLogo/cp_img_tj.png";
                market.webInfo.PagelaodImgUrl = "/Content/webImgs/upLogo/cp_img_tj.png";
                market.webInfo.LogoImgUrl = "/Content/webImgs/upLogo/cp_img_tj.png";
                market.webInfo.WxShareImg = "/Content/webImgs/upLogo/cp_img_tj.png";
                market.webInfo.BtnCodeImgUrl = "/Content/webImgs/upLogo/cp_img_tj.png";
                market.webInfo.BtnName = "自定义按钮";
                market.webInfo.IsShare = 1;
            }

            return View(market);
        }
        #endregion


        public ActionResult AddAwards()
        {
            return View();
        }
        #endregion

        #region 奖池管理
        public ActionResult JackpotManage()
        {
            return View();
        }
        public ActionResult JackpotDetails(int jid, int type, int couponType=0)
        {
            ViewBag.jid = jid;
            ViewBag.type = type;
            ViewBag.couponType = couponType;
            return View();
        }
        public ActionResult CreateCoupon()
        {
            return View();
        }
        public ActionResult CreateRP()
        {
            return View();
        }
        public ActionResult CreateFlow()
        {
            return View();
        }
        public ActionResult FlowRecharge()
        {
            return View();
        }

        #endregion

        #region 促销页面管理
        public ActionResult PromotionManage()
        {
            return View();
        }
        public ActionResult CreateTemplate()
        {
            return View();
        }
        public ActionResult EditTemplate()
        {
            return View();
        }
        
        #endregion

        #region 活动管理
        public ActionResult ActivitiesManage()
        {
            return View();
        }
        public ActionResult PreviewRed()
        {
            return View();
        }
        public ActionResult PreviewTurntable()
        {
            return View();
        }
        public ActionResult WebTemplate1_1()
        {
            return View();
        }
        public ActionResult WebTemplate1_2()
        {
            return View();
        }
        public ActionResult WebTemplate1_3()
        {
            return View();
        }
        
        /// <summary>
        /// 中奖明细
        /// </summary>
        /// <returns></returns>
        public ActionResult Thewinning()
        {
            return View();
        }
       
        #endregion

        #region 客户信息
        
        //public ActionResult ClientManage() 
        //{
        //    return View();
        //}

        public ActionResult CustomerInfo() 
        {
            return View();
        }

        public ActionResult CustomerParticulars() 
        {
        //    string str = "您好，您所查询的Elastagen优弹素是正牌产品的标识，欢迎您再次选购！";
        // string[] arr=   System.Text.RegularExpressions.Regex.Split(str, "Elastagen优弹素");
        //str= arr[0] + "Elastagen优弹素当前时间为" + DateTime.Now + arr[1];
        //    str.Split();
            return View();
        }

        public ActionResult CustomerRecord(int uID)
        {
            ViewBag.uid = uID;
            return View();
        }


        public ActionResult GiveData()                                     
        {
            return View();
        }


        

        public JsonResult MarketUserList(string msearch, int pageIndex = 1, int pageSize = 10)
        {
            PagerModel pm = new PagerModel();
            pm.Page = pageIndex;
            pm.PageSize = pageSize;
            DBHService _dbhService = new DBHService();
           string msearchBase64= Base64Helper.Base64Encode(msearch);
            string TblUserName = @"Marketing_User" + LogOnUser.ECode;
            string TblThewinningName = @"Marketing_thewinning" + LogOnUser.ECode;
            if (_dbhService.TabExists("Marketing", TblUserName) )
            {
                pm.StrCondition = "     (Nickname like '%" + msearchBase64 + "%' or Phone like '%" + msearch + "%') ";
            if (LogOnUser.Distributor != 0)
            {
                pm.StrCondition += " and ChangeLoginID=" + LogOnUser.UserID;
            }
            var model = _market.GetMarketingUserService(ref pm,msearch,LogOnUser.ECode);
            return Json(model);
            }
            return Json("");
        }

        #region 导出EXCEl
        public ActionResult MarketManageExecl(string msearch)
        {
            var model = _market.GetExecls(msearch,LogOnUser.ECode);
            var _byte_query = Excel.Exprot<Marketing_User>(model.ToList(), new string[] { "客户名称", "会员等级", "联系电话", "地址", "参与活动次数" }, p =>
            {
                return new object[] { 
				p.Nickname,
				p.Provnice,
				p.Phone,
				p.City,
				p.Country,
				p.OA_Time
				};
            }, "antifake");
            return File(_byte_query, "application/octet-stream", string.Format("{0}.xls", DateTime.Now.ToString("yyyyMMddHHmmssfff")));
        }
        #endregion

        #region 会员等级
        
        public ActionResult MemberLevel()
        {
            return View();
     	}

        #endregion


    
        //  #region 客户管理
        //public ActionResult CustomerManage()
        //{
        //    return View();
        //}

        //#endregion

        //  #region 客户信息
        //public ActionResult CustomerInfo()
        //{
        //    return View();
        //}

        //#endregion

        //  #region 会员等级
        //public ActionResult MembershipGrade()
        //{
        //    return View();
        //}

        //#endregion

        /// <summary>
        /// 中奖率控制
        /// 2017年7月27日14:45:02
        /// Dy
        /// </summary>
        ///  <param name="list">Sequence排序好的奖项list</param>
        /// <returns></returns>
        public Marketing_Awards getRandomAwards(List<Marketing_Awards> list)
        {
            var rand = new Random();
            int i = rand.Next(1, 10001);
            double index = 0;      
            double end = 0;
            Dictionary<double, double> rate = new Dictionary<double, double>();
            Marketing_Awards a = new Marketing_Awards();
            foreach (var item in list)
            {
                end += double.Parse(item.Rate.ToString()) * 100;
                rate.Add(index, end);
                if (i >= index && i <= end)
                {
                    //判断奖池有没有奖品 
                    if (item.ResidueNums <= 0)
                    {
                        a.Congrats = "没有中到奖品！";
                        a.EnterpriseName = list[0].EnterpriseName;
                        a.Denomination = -1;
                        return a;
                    }
                    item.ResidueNums = item.ResidueNums - 1;

                    Marketing_Jackpot j = _market.GetJackpotModel(int.Parse(item.JackpotID.ToString()));
                    //手气红包
                    if (j.Type == 1 && j.CouponType == 0)
                    {
                        item.Denomination = Convert.ToDecimal(GetLuckRadPacket(j, item));
                    }
                    else if (j.ResidueMoney != null)
                    {
                        item.ResidueMoney = item.ResidueMoney - item.Denomination;
                    } 
                    return item;
                }
                index = end;
            }

            a.Congrats = "没有中到奖品！";
            a.EnterpriseName = list[0].EnterpriseName;
            a.Denomination = -1;
            return a;
        }


        /// <summary>
        /// 运气红包
        /// 2017年7月27日14:45:02
        /// Dy
        /// </summary>
        /// <returns></returns>
        public double GetLuckRadPacket(Marketing_Jackpot jackpot, Marketing_Awards awards)
        {
            if (awards.ResidueNums == 1)
            {
                return double.Parse(awards.ResidueMoney.ToString());
            }
            Random rand = new Random();
            int min = Convert.ToInt32(jackpot.MinDenomination) * 100;
            double maxTimes = Convert.ToDouble(jackpot.TotalMoney / awards.TotalNums) * 2 > 5 ? 5 : Convert.ToDouble(jackpot.TotalMoney / jackpot.TotalNums) * 2;
            int max = Convert.ToInt32(maxTimes) * 100;
            double money = rand.Next(min, max);
            return money / 100;
        }


    
        #endregion

        public ActionResult GiveHongBao()
        {
           
            return View();
        }

        #region 主界面视图显示领取记录
 
        //领取金额排行


        #endregion

     

        /// <summary>
        /// 判断是否有活动 有就返回活动
        /// </summary>
        /// <param name="codeStr">解密的code</param>
        /// <returns>b: 0 没有活动  1 有活动返回活动model</returns>
        public Hashtable IsMarketing(string fwCode)
        {
 
                AntiFakeVerifyService _AntiFakeVerifyService=new AntiFakeVerifyService();

                DataTable dt= _AntiFakeVerifyService.GetCodeModel(fwCode, "Fw_CodeSecret");
                string jiemiCode = string.Empty;
                int eid;
                Hashtable ht = new Hashtable();
                if (dt.Rows.Count!=0)
                {
                   jiemiCode=dt.Rows[0]["Fw_Code"].ToString();
                   eid = int.Parse(dt.Rows[0]["EnterpriseId"].ToString());
                }
                else //码不存在
                {
                    ht.Add("b", 0);
                    return ht;
                }
                ManagerService _manager = new ManagerService();
                Organization_Enterprise model=_manager.GetEnterpriseModel_Eid(eid);
                string bid = jiemiCode.Substring(model.Code.Length, AppConst.SubBatchLen);
                Marketing_Activity activity = _market.GetActivity_Issue(eid, bid);
                if (activity==null)
                {
                    ht.Add("b", 0);
                    ht.Add("model", new Marketing_Activity() );
                    return ht ;
                }
                ht.Add("b", 1);
                ht.Add("model", activity);
                return ht;
        }

       
       
    }
}